<template>
	<view class="pages">
		<mvBar :mysNavConfig="mysNavConfig">
			<view slot="right" class="right">
				<image class="img" style="width: 16px;height: 16px;" src="/static/sort_w.png"></image>
			</view>
		</mvBar>
		<view class="title" style="font-size: 1rem;margin: 10px 0;padding-bottom: 8px;border-bottom: 1px solid #555;">
			<text>{{ searchParentName }}</text>
		</view>
		<block>
			<view class="search-result">
				<scroll-view show-scrollbar="true" :style="{ height: scrollHeight + 'px' }" scroll-y="true"
					:refresher-enabled="isOpenRefresh" :refresher-triggered="triggered" :refresher-threshold="100"
					refresher-background="gray" @scrolltolower="scrolltolowerFun" @refresherpulling="onPulling"
					@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort">
					<view class="search-result-word">
						<shortlist :list="dataList" :httpParams="httpParams" />
					</view>
					<uni-load-more v-if="!isOpenRefresh" iconType="circle" :status="status" />
					<!-- <view style="height: calc(100rpx + env(safe-area-inset-bottom))">
					</view> -->
				</scroll-view>
			</view>
		</block>
	</view>
</template>

<script>
	import shortlist from '@/components/vertical.vue'
	import mvBar from "@/components/mys_navBar/mysNavBar";
	import request from '@/common/request'
	import store from '@/store/index.js'
	import mysNavConfig from '@/pages/series/seriesNavConfig.js';
	import {
		mapGetters,
		mapActions
	} from 'vuex' // 引入辅助函数

	export default {
		components: {
			shortlist,
			mvBar
		},
		data() {
			return {
				dataList: [],
				videoCount: 0,
				videoPageNo: 1,
				videoPageSize: 100,
				loading: false, // 加载状态锁（防止重复请求）
				isActive: false,
				triggered: false,
				isOpenRefresh: true, // 是否开启下拉
				status: 'noMore',
				hasMore: true,
				scrollHeight: 0, // 滚动区域高度
				searchBarHeight: 80, // 搜索框高度(rpx)
				windowWidth: 0, //获取屏幕宽度🌟💗
				windowHeight: 0,
				tabberHeight: 0, //测试高度🌟💗
				searchParentId: "",
				genreIds: "",
				tagIds: "",
				searchParentName: "",
				httpParams: {},
				mysNavConfig: mysNavConfig,
			};
		},
		computed: {
			// 通过 mapGetters 获取 Vuex 中的数据
			...mapGetters([
				'getSeriesParams'
			]),
			seriesParams() {
				return this.getSeriesParams || {}
			},
			styleWidthHeight() {
				return `width: ${this.windowWidth}px; height: ${ this.windowHeight - this.tabberHeight }px;`
			}
		},
		onLoad() {
			// 计算滚动区域高度
			this.calculateScrollHeight();

			// 监听窗口尺寸变化，重新计算高度
			uni.onWindowResize(() => {
				this.calculateScrollHeight();
			});
			this.requestReset()
			this._freshing = false;
			
			this.windowWidth = uni.getSystemInfoSync().screenWidth
			this.windowHeight = uni.getSystemInfoSync().screenHeight

			this.platform = uni.getSystemInfoSync().platform
			const model = uni.getSystemInfoSync().model
			if (
				this.platform == 'ios' &&
				(model !== 'iPhone6' ||
					model !== 'iPhone6s' ||
					model !== 'iPhone7' ||
					model !== 'iPhone8')
			) {
				this.tabberHeight = 50 + 32
			} else {
				this.tabberHeight = 50
			}
			// 将传输的数据赋值
			this.searchParentId = this.seriesParams.ParentId
			this.searchParentName = this.seriesParams.ParentName
			this.genreIds = this.seriesParams.GenreIds
			this.tagIds = this.seriesParams.TagIds
			this.getSearchList()
		},
		onUnload() {
			// 移除窗口尺寸变化监听
			uni.offWindowResize((res) => {});
		},
		watch: {
		  
		},
		methods: {
			back(){
				uni.navigateBack({
					delta:1
				})
			},
			calculateScrollHeight() {
				// 获取系统信息
				uni.getSystemInfo({
					success: (res) => {
						// 将rpx转换为px (750rpx = 屏幕宽度)
						const pxPerRpx = res.windowWidth / 750;
						const searchBarHeightPx = this.searchBarHeight * pxPerRpx;
						// 滚动区域高度 = 窗口高度 - 搜索框高度
						this.scrollHeight = res.windowHeight - searchBarHeightPx - 100;
					}
				});
			},
			focus() {
				this.isActive = true;
			},
			blur() {
				this.isActive = false;
			},
			/**
			 * 搜索
			 * @param {Object} word
			 */
			async getSearchList() {
				//搜索结果成功以后再跳 this.show = 2;
				if (this.loading || !this.hasMore) {
					return;
				}
				uni.showLoading({
					title: '搜索中'
				});
				let userTmp1 = uni.getStorageSync('user')
				if (!userTmp1) {
					return
				}
				this.loading = true;
				let userTmp = JSON.parse(userTmp1)
				this.videoPageNo = (this.videoPageNo <= 0 ? 1 : this.videoPageNo)
				let getJSON = {
					Fields: "BasicSyncInfo,CanDelete,PrimaryImageAspectRatio,ProductionYear,Status,EndDate,Width,Height,Size,Tags,DateCreated",
					StartIndex: (this.videoPageNo - 1) * this.videoPageSize,
					SortBy: "SortName",
					SortOrder: "Ascending",
					EnableImageTypes: "Primary,Backdrop,Thumb",
					ImageTypeLimit: 1,
					Recursive: true,
					ParentId: this.searchParentId,
					GenreIds: this.genreIds,
					TagIds: this.tagIds,
					IncludeItemTypes: "Movie,Series,Video,Game,MusicAlbum,Playlist,BoxSet",
					GroupProgramsBySeries: true,
					IncludeSearchTypes: false,
					Limit: this.videoPageSize
				}
				let urlAppend = this.$g.jsonToGetParams(getJSON)
				let requestUrlShort = `/emby/Users/${userTmp.userId}/Items`
				let requestUrl = `${requestUrlShort}${urlAppend}`
				const data = await request.get(requestUrl)
				let videoList = data.Items
				this.videoCount = data.TotalRecordCount
				// console.log("请求返回数据" + JSON.stringify(videoList))
				if (!videoList || videoList.length == 0) {
					this.hasMore = false;
					this.loading = false;
					uni.hideLoading();
					return
				}
				let serverUrl = `${userTmp.serverip}:${userTmp.serverport}`
				if (!serverUrl.startsWith('http')) {
					serverUrl = `http://${serverUrl}`
				}
				for (const item of videoList) {
					let imageStr = `${serverUrl}/emby/Items/${item.Id}/Images/Primary`
					item.cover = imageStr
					item.playIng = false
				}
				this.dataList = [...this.dataList, ...videoList];
				uni.hideLoading();
				this.loading = false; // 释放锁
				this.httpParams = {
					params: getJSON,
					url: requestUrlShort
				}
			},
			requestReset() {
				this.hasMore = true;
				this.videoPageNo = 1;
				this.dataList = []
			},
			navigatorSearch() {
				this.requestReset();
				this.show = 1;
				this.searchWord = '';
			},
			// 自定义下拉刷新控件被下拉
			onPulling(e) {
				// console.log("onpulling", e);
				if (e.detail.deltaY < 0) return // 防止上滑页面也触发下拉
				this.triggered = true;
			},
			// 自定义下拉刷新被触发
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				setTimeout(() => {
					this.triggered = false;
					this._freshing = false;
					this.requestReset();
					this.getSearchList(this.searchWord)
				}, 500);
			},
			// 自定义下拉刷新被复位
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},
			// 自定义下拉刷新被中止
			onAbort() {
				console.error("onAbort");
			},
			//上拉加载，页面滑动到底部加载分页数据
			scrolltolowerFun() {
				if (!this.hasMore) {
					this.status = 'noMore';
					return
				}
				this.status = 'loading'
				this.videoPageNo++
				this.getSearchList(this.searchWord)
			}
		}
	}
</script>

<style lang="scss">
	.pages {
	}

	.index-search {
		height: 80rpx;
		padding: 16rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		margin: 40rpx 30rpx 30rpx 30rpx;
		background-color: #f7f7f7;
		border-radius: 50rpx;
		box-sizing: border-box;

		image {
			width: 26rpx;
			height: 26rpx;
			margin-left: 20rpx;
			margin-right: 20rpx;
		}

		#cancel {
			margin-left: 200rpx;
		}

		.index-search-left {
			display: flex;
			justify-content: space-around;
			align-items: center;
			position: relative;

			input {
				position: relative;
				z-index: 2;
				background: #ffffff;
				color: #000000;
			}

			.pic {
				height: 24rpx;
				width: 24rpx;
				position: absolute;
				z-index: 1;
				top: 0;
				left: 200rpx -12rpx;
				transition: top 0.3s;
			}

			.pic.active {
				top: -24rpx;
			}
		}
	}

	.search-history {
		.search-history-head {
			display: flex;
			flex-direction: row;
			margin: 0 16rpx;
			font-size: 28rpx;
			justify-content: space-between;

			image {
				width: 35rpx;
				height: 35rpx;
				margin-left: 35rpx;
				margin-right: 35rpx;
			}
		}

		.search-history-list {
			display: flex;
			margin-top: 20rpx;
			flex-wrap: wrap;

			.item {
				border-radius: 10rpx;
				padding: 2rpx 10rpx;
				margin: 5rpx 30rpx;
				word-wrap: break-word;
				white-space: normal;
				overflow: hidden;
				display: flex;
				align-items: center;
			}
		}
	}

	.search-hot {
		.search-hot-head {
			margin: 0 30rpx;
			margin-top: 10rpx;
			font-size: 30rpx;
		}

		.search-hot-item {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			background: #f7f7f7;
			border-radius: 30rpx;
			margin: 30rpx 30rpx;
			padding: 10rpx;

			.search-hot-left {
				padding-top: 20rpx;
			}

			.search-hot-main {
				font-size: 35rpx;
				display: flex;
				align-items: center;
				padding-left: 20rpx;

				image {
					width: 20rpx;
					height: 20rpx;
					margin-left: 5rpx;
				}

				.second {
					margin-left: 20rpx;
				}

				.search-hot-main-bot {
					font-size: 25rpx;
				}
			}

			.search-hot-right {
				padding-top: 20rpx;
				font-size: 29rpx;
			}
		}
	}

	.search-result-word {
		.search-result-word {
			margin-top: 20rpx;
		}
	}

	.title {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.sort-contain {
			--tw-text-opacity: 1;
			color: #BCB6B8;
			line-height: 1.5rem;
			font-weight: 500;
			font-size: 1rem;
			margin-right: 5px;
			display: flex;
			align-items: center;

			.sort-db {
				margin-right: 20px;
			}
		}

		.type-contain {
			--tw-text-opacity: 1;
			color: #BCB6B8;
			line-height: 1.5rem;
			font-weight: 500;
			font-size: 1rem;
			margin-right: 5px;
			display: flex;
			align-items: center;

			.type-db {
				// margin-right: 50px;
			}
		}

	}
	.dropdown-filter{
		height: 110rpx;
	}
</style>